import pygame
import sys
from bullet import Bullet
from alien import Alien
from time import sleep


def check_events(ai_settings, screen, stats, sb, play_button, ship, aliens, bullets):
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            check_keydown_events(screen, ship, event, bullets, ai_settings)
        elif event.type == pygame.KEYUP:
            check_keyup_events(ship, event)
        elif event.type == pygame.MOUSEBUTTONDOWN:
            mouse_x, mouse_y = pygame.mouse.get_pos()
            check_play_button(ai_settings, screen, stats, sb, play_button, ship,
                              aliens, bullets, mouse_x, mouse_y)


def update_screen(ai_settings, screen, stats, sb, ship, bullets, aliens,
                  play_button):
    screen.fill(ai_settings.bg_color)
    for bullet in bullets:
        bullet.draw_bullet()

    ship.blitme()
    aliens.draw(screen)
    sb.show_score()

    if not stats.game_active:
        play_button.draw_button()

    # 让最近绘制的图像可见
    pygame.display.flip()


def update_bullets(ai_settings, screen, stats, sb, ship, aliens, bullets):
    bullets.update()
    for bullet in bullets.copy():
        if bullet.rect.right <= 0:
            bullets.remove(bullet)

    check_bullet_alien_collisions(ai_settings, screen, stats, sb, ship, bullets, aliens, )


def check_bullet_alien_collisions(ai_settings, screen, stats, sb, ship, bullets, aliens):
    # 检查是否有子弹击中了外星人
    # 如果击中，就删除相应的子弹和外星人
    collisions = pygame.sprite.groupcollide(bullets, aliens, True, True)

    if collisions:
        for aliens in collisions.values():
            stats.score += ai_settings.alien_points * len(aliens)
            sb.prep_score()
        check_high_score(stats, sb)

    if len(aliens) == 0:
        # 删除现有的子弹并新建一群外星人
        # 如果整群外星人都被消灭，就提高一个等级
        bullets.empty()
        ai_settings.increase_speed()
        # 提高等级
        stats.level += 1
        sb.prep_level()
        create_fleet(ai_settings, screen, ship, aliens)


def check_keydown_events(screen, ship, event, bullets, ai_settings):
    if event.key == pygame.K_UP:
        ship.moving_up = True
    elif event.key == pygame.K_DOWN:
        ship.moving_down = True
    elif event.key == pygame.K_LEFT:
        ship.moving_left = True
    elif event.key == pygame.K_RIGHT:
        ship.moving_right = True
    elif event.key == pygame.K_SPACE:
        fire_bullet(bullets, screen, ship, ai_settings)
    elif event.key == pygame.K_q:
        sys.exit()


def fire_bullet(bullets, screen, ship, ai_settings):
    if len(bullets) < ai_settings.bullets_allowed:
        new_bullets = Bullet(screen, ship, ai_settings)
        bullets.add(new_bullets)


def check_keyup_events(ship, event):
    if event.key == pygame.K_UP:
        ship.moving_up = False
    if event.key == pygame.K_DOWN:
        ship.moving_down = False
    if event.key == pygame.K_RIGHT:
        ship.moving_right = False
    if event.key == pygame.K_LEFT:
        ship.moving_left = False


def get_number_aliens_x(ai_settings, alien_width):
    alien_interval = ai_settings.alien_interval
    available_space_y = ai_settings.screen_lenth - (alien_width + alien_interval)
    number_aliens_y = int(available_space_y / (alien_width + alien_interval))
    return number_aliens_y


def get_aliens_column(ai_settings, ship_width, alien_width):
    available_space_x = ai_settings.screen_width - (ship_width + 3 * alien_width)
    number_columns = int(available_space_x / (2 * alien_width))
    return number_columns


def create_alien(ai_settings, screen, aliens, alien_number, column_number):
    alien = Alien(ai_settings, screen)
    alien_interval = ai_settings.alien_interval
    alien_width = alien.rect.height
    alien.y = alien_interval + (alien_width + alien_interval) * alien_number
    alien.rect.y = alien.y
    alien.rect.x = alien.rect.width + 2 * alien_width * column_number
    aliens.add(alien)


def create_fleet(ai_settings, screen, ship, aliens):
    # 创建一个外星人，并计算一列最大可以容纳多少个外星人
    alien = Alien(ai_settings, screen)
    number_aliens_x = get_number_aliens_x(ai_settings, alien.rect.height)
    number_columns = get_aliens_column(ai_settings, ship.rect.width,
                                       alien.rect.width)

    for alien_number in range(number_aliens_x):
        for column_number in range(number_columns):
            create_alien(ai_settings, screen, aliens, alien_number, column_number)


def check_fleet_edges(ai_settings, aliens):
    for alien in aliens.sprites():
        if alien.check_edges():
            change_fleet_direction(ai_settings, aliens)
            break


def change_fleet_direction(ai_settings, aliens):
    for alien in aliens.sprites():
        alien.rect.x += ai_settings.fleet_speed
    ai_settings.fleet_direction *= -1


def ship_hit(ai_settings, stats, sb, screen, ship, aliens, bullets):
    # 将ships_left减一
    # stats.ships_left -= 1

    # 清空外星人列表和子弹列表
    aliens.empty()
    bullets.empty()
    if stats.ships_left > 0:
        stats.ships_left -= 1
        sb.prep_ships()
        create_fleet(ai_settings, screen, ship, aliens)
        ship.center_ship()
        sleep(0.5)
    else:
        stats.game_active = False
        pygame.mouse.set_visible(True)


def check_aliens_right(ai_settings, stats, sb, screen, ship, aliens, bullets):
    screen_rect = screen.get_rect()
    for alien in aliens.sprites():
        if alien.rect.right >= screen_rect.right:
            ship_hit(ai_settings, stats, sb, screen, ship, aliens, bullets)
            break


def update_aliens(ai_settings, stats, sb, screen, ship, aliens, bullets):
    check_fleet_edges(ai_settings, aliens)
    aliens.update()

    # 检测外星人和飞船之间的碰撞
    if pygame.sprite.spritecollideany(ship, aliens):
        ship_hit(ai_settings, stats, sb, screen, ship, aliens, bullets)
    # 检查是否有外星人抵达屏幕底端
    check_aliens_right(ai_settings, stats, sb, screen, ship, aliens, bullets)


def check_play_button(ai_settings, screen, stats, sb, play_button, ship, aliens,
                      bullets, mouse_x, mouse_y):
    button_clicked = play_button.rect.collidepoint(mouse_x, mouse_y)
    if button_clicked and not stats.game_active:
        ai_settings.initialize_dynamic_settings()
        pygame.mouse.set_visible(False)

        stats.reset_stats()
        stats.game_active = True

        # 重置游戏统计信息
        stats.reset_stats()
        stats.game_active = True
        # 重置记分牌图像
        sb.prep_score()
        sb.prep_high_score()
        sb.prep_level()
        sb.prep_ships()
        # 清空外星人列表和子弹列表
        aliens.empty()
        bullets.empty()

        create_fleet(ai_settings, screen, ship, aliens)
        ship.center_ship()


def check_high_score(stats, sb):
    if stats.score > stats.high_score:
        stats.high_score = stats.score
        sb.prep_high_score()
